package com.leyou.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.gateway.config.OSSProperties;
import com.leyou.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService{

    @Autowired
    private OSSProperties prop;

    @Autowired
    private OSS client;


    /*上传文件
    * 1.采用ImageIO校验图片
    * 2.获取文件名和后缀（采用字符串截取）
    * 3.设置新文件名（UUID）
    * 4.将图片资源上传存储在nginx服务器上，所以要将图片存储至nginx
    * 的html文件目录下 上传路径 StringPath="";
    * 5.创建该目录的文件对象，判断是否存在的逻辑处理
    * 6.上传文件
    * 7.返回拼接的url
    *
    *
    *
    *
    *
    *
    *
    *
    * */
    @Override
    public String upload(MultipartFile file) {

        /*采用ImageIO校验图片*/
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if(image==null){
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        /*获取文件名和后缀*/
        String fileName=file.getOriginalFilename();
       // substring 包括索引处的字符
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        /*设置新文件名*/
        String  newFileName= UUID.randomUUID().toString()+suffix;

        /*上传文件到nginx服务器*/
        String path="D:\\Pensenol\\nginx-1.14.0\\html";

        File file1 = new File(path);
        if(!file1.exists()){
            file1.mkdirs();
            /* mkdir()是创建子目录  mkdir()只会建立一级的文件夹
              mkdirs()是创建多级目录。mkdirs()可以建立多级文件夹
             * */
        }
        /*创建上传图片的文件, 把文件上传到目录*/
        File newFile = new File(file1, newFileName);
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw  new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
        /*返回url*/
        String url="http://image.leyou.com/"+newFileName;

        return url;
    }

    public Map<String, Object> getSignature() {
        try {
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
